public class GeoCodeHelper {
	
	public class GeoCode{
		String latitude;
		String longitutde;
		public Boolean success;
        public String statusMsg;
	}
	@future (callout= true)
	public static void populateGeoCode(Set<Id> branchIds){
		Branch__c[] branches = [Select Id, Latitude__c, Longitude__c, City__c, Company__c, Company__r.Latitude__c,  Company__r.Longitude__c from Branch__c where Id in: branchIds];
		List<Branch__c> branchForUpdate = new List<Branch__c>();
		GeoCode geoDataTemp;
		for(Integer i=0; i<branches.size(); i++){
			geoDataTemp = GeoCodeIntegration(branches[i].City__c);
			branches[i].Latitude__c = geoDataTemp.latitude;
			branches[i].Longitude__c = geoDataTemp.longitutde;
			branchForUpdate.add(branches[i]);
		}
		if(branchForUpdate.size()>0){
			update branchForUpdate;
		}
	}
	
	public static GeoCode GeoCodeIntegration(String address){
		GeoCode geocodeData = new GeoCode();
		
		Http h = new Http();
		HttpRequest req = new HttpRequest();
		req.setEndpoint('http://maps.google.com/maps/geo?q='+address+'&output=xml&sensor=false&key=ABQIAAAAXFPSHN_yErY9HaCMcMpzBhQWey-B1ZKQhVHInL6_tETDfQStQxQhMwZwcgmJCLVfRrjvTAwLi7uUYw');
		req.setMethod('GET');
		HttpResponse res = h.send(req);
		String resStr = res.getBody();
		System.debug('*******'+resStr);
		XMLDom dom = new XMLDom(resStr);
		XMLDom.Element point = dom.getElementByTagName('Point');
		String pointStr;
		if(point != null){
			pointStr = point.getValue('Coordinates');
			System.debug('****'+pointStr.split(',')[0]+'*****'+pointStr.split(',')[1]);
			geocodeData.latitude = pointStr.split(',')[1];
			geocodeData.longitutde = pointStr.split(',')[0];
		}
		else{
            geocodeData.success = false;
            geocodeData.statusMsg = 'Address Not Found';
        }
		return geocodeData;
		
	}
	public static Double calculateDistance(Double pointLat, Double pointLong, Double centreLat, Double centreLong){
		Double a, dLat, dLong, tempLat, tempLong, c;
		Double R = 6371;
		
		tempLat = pointLat/57.29577951;
		tempLong = pointLong/57.29577951;
		centreLat = centreLat/57.29577951;
		centreLong = centreLong/57.29577951;
		
		dLat = centreLat - tempLat;
		dLong = centreLong - tempLong;
		a =  Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(tempLat) * Math.cos(centreLat) * Math.sin(dLong/2) * Math.sin(dLong/2);
		c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));  
		
		return R*c;
		
	}
}